import django_filters
from django.db.models import Count
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response

from message import models
from message import serializers
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import FilterSet,DjangoFilterBackend


# Create your views here.

class AuthorPage(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'


class AuthorView(viewsets.ModelViewSet):
    queryset = models.Author.objects.all()
    serializer_class = serializers.AuthorSer

    pagination_class = AuthorPage
    @action(detail=False,methods=['get'])
    def br(self,request):
        b1 = models.Author.objects.annotate(number=Count('message')).values('name','number').order_by('-number')
        return Response(b1[0:3])

class MessagePage(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'size'

class MessageFil(FilterSet):
    titles = django_filters.CharFilter(field_name='title',lookup_expr='contains')
    authors = django_filters.CharFilter(field_name='author')
    aut = django_filters.CharFilter(field_name="au")
    class Meta:
        model = models.Message
        fields = ['titles','authors','aut']

class MessageView(viewsets.ModelViewSet):
    queryset = models.Message.objects.all()
    serializer_class = serializers.MessageSer
    filter_backends = [DjangoFilterBackend,OrderingFilter]
    filterset_class = MessageFil
    pagination_class = MessagePage

    ording_fields = ['read']
    ording = ['read']

    @action(detail=True,methods=['put'])
    def brs(self,request,pk):
       a = models.Message.objects.filter(id=pk).first()
       a.is_show = request.data.get('show')
       # a.is_show = not a.is_show
       a.save()
       return Response({'msg':'ok'})









